//
//  AuthenVC.swift
//  kxf
//
//  Created by Mac on 2024/3/28.
//

import Foundation
import MCToast

class AuthenVC: WHBaseViewVC {
    
    var idFrontMsgDict = NSDictionary()
    var idBackMsgDict = NSDictionary()
    var bankMsgDict = NSDictionary()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
    }
    lazy var photoVm : AuthenVerifyPhotoVM = {
        let vm = AuthenVerifyPhotoVM.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 0))
        vm.controller = self
        vm.idOcrFrontBlock = {(dict)in
            self.idFrontMsgDict = dict
            self.updateIdCardFrontMsg()
        }
        vm.idOcrBackBlock = {(dict)in
            self.idBackMsgDict = dict
            self.udpateIdCardBackMsg()
        }
        vm.bankOcrFrontBlock = {(dict)in
            self.bankMsgDict = dict
            self.udpateBankCardBackMsg()
        }
        return vm
    }()
    lazy var msgVm : AuthenVerifyMsgVM = {
        let vm = AuthenVerifyMsgVM.init(frame: CGRect.init(x: 0, y: self.photoVm.frame.maxY+kFitWidth(10), width: 0, height: 0))
        vm.controller = self
        return vm
    }()
    lazy var nextBtn : UIButton = {
        let btn = UIButton()
        btn.frame = CGRect.init(x: kFitWidth(31), y: self.msgVm.frame.maxY+kFitWidth(40), width: kFitWidth(316), height: kFitWidth(48))
        btn.setTitle("下一步", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.setBackgroundImage(UIImage.init(named: "button_theme_bg"), for: .normal)
        btn.layer.cornerRadius = kFitWidth(24)
        btn.clipsToBounds = true
        btn.titleLabel?.font = .systemFont(ofSize: 16, weight: .regular)
        btn.backgroundColor = .clear
        
        btn.addTarget(self, action: #selector(nextAction), for: .touchUpInside)
        
        return btn
    }()
}

extension AuthenVC{
    @objc func nextAction() {
//        "xinming":"\(msgVm.idNameVm.textField.text ?? "")",
//        "shenfengid":"\(msgVm.idNoVm.textField.text ?? "")",
//        "bankcardid":"\(msgVm.bankNoVm.textField.text ?? "")",
//        "shenfengzhengpic":"\(photoVm.idCardFrontImgUrl)",
//        "shenfengfanpic":"\(photoVm.idCardBackImgUrl)",
//        "bankcardpic":"\(photoVm.bankCardFrontImgUrl)",
//        "hasHoldingCard":false,
//        "openingBank":"\(msgVm.bankBranchVm.rightLabel.text ?? "")",
        if photoVm.idCardFrontImgUrl.count < 2 {
            MCToast.mc_text("请上传身份证人像面")
            return
        }
        if photoVm.idCardBackImgUrl.count < 2 {
            MCToast.mc_text("请上传身份证国徽面")
            return
        }
        if photoVm.bankCardFrontImgUrl.count < 2 {
            MCToast.mc_text("请上传银行卡卡号照")
            return
        }
        if msgVm.idNameVm.textField.text?.count ?? 0 < 2 {
            MCToast.mc_text("请输入证件姓名")
            return
        }
        if msgVm.idNoVm.textField.text?.count ?? 0 < 10 {
            MCToast.mc_text("请输入证件号码")
            return
        }
        if msgVm.bankNoVm.textField.text?.count ?? 0 < 8 {
            MCToast.mc_text("请输入银行卡号")
            return
        }
        if !judgePhoneNumber(phoneNum: msgVm.phoneVm.textField.text ?? ""){
            MCToast.mc_text("请输入正确的手机号")
            return
        }
        if msgVm.bankBranchVm.rightLabel.text?.count ?? 0 < 1 {
            MCToast.mc_text("请选择开户支行")
            return
        }
        
        sendCertRequest()
    }
}

extension AuthenVC{
    func initUI() {
        initNavi(titleStr: "实名认证")
        
        view.backgroundColor = .COLOR_LIGHT_GREY
        view.addSubview(scrollView)
        scrollView.frame = CGRect.init(x: 0, y: getNavigationBarHeight()+kFitWidth(10), width: SCREEN_WIDHT, height: SCREEN_HEIGHT-getNavigationBarHeight())
        
        scrollView.addSubview(photoVm)
        scrollView.addSubview(msgVm)
        scrollView.addSubview(nextBtn)
        
        scrollView.contentSize = CGSize.init(width: 0, height: self.nextBtn.frame.maxY + kFitWidth(20))
        scrollView.backgroundColor = .COLOR_LIGHT_GREY
    }
    func updateIdCardFrontMsg() {
        msgVm.idNameVm.textField.text = self.idFrontMsgDict["name"]as? String ?? ""
        msgVm.idNoVm.textField.text = self.idFrontMsgDict["code"]as? String ?? ""
//        msgVm.idAddressVm.textField.text = self.idFrontMsgDict["address"]as? String ?? ""
    }
    func udpateIdCardBackMsg() {
//        msgVm.idStartTimeVm.setLabelContent(content: Date().changeDateFormatter(dateString: "\(idBackMsgDict["issueDate"]as? String ?? "")"))
//        msgVm.idEndTimeVm.setLabelContent(content: Date().changeDateFormatter(dateString: "\(idBackMsgDict["expiryDate"]as? String ?? "")"))
//
    }
    
    func udpateBankCardBackMsg() {
//        msgVm.bankNameVm.textField.text = bankMsgDict["bank_name"]as? String ?? ""
        let bankNo = bankMsgDict["bank_card_number"]as? String ?? ""
        msgVm.bankNoVm.textField.text = bankNo.replacingOccurrences(of: " ", with: "")
    }
}


extension AuthenVC{
    func sendCertRequest() {
        MCToast.mc_loading()
        let param = ["tel":"\(UserModel.shared.phone)",
                     "type":"1",
                     "xinming":"\(msgVm.idNameVm.textField.text ?? "")",
                     "shenfengid":"\(msgVm.idNoVm.textField.text ?? "")",
                     "bankcardid":"\(msgVm.bankNoVm.textField.text ?? "")",
                     "shenfengzhengpic":"\(photoVm.idCardFrontImgUrl)",
                     "shenfengfanpic":"\(photoVm.idCardBackImgUrl)",
                     "bankcardpic":"\(photoVm.bankCardFrontImgUrl)",
                     "hasHoldingCard":false,
                     "openingBank":"\(msgVm.bankBranchVm.rightLabel.text ?? "")",
                     "merchantType":"2",
                     "accBankType":"2",
                     "bankTel":"\(msgVm.phoneVm.textField.text ?? "")"] as [String : AnyObject]
        WHNetworkUtil.shareManager().POST(urlString: URL_authen_user_cert, parameters: param ,isNeedToast: true,vc: self) { responseObject in
            DLLog(message: "\(responseObject)")
            MCToast.mc_remove()
            
            let data = responseObject["data"]as? NSDictionary ?? [:]
            if data["smsNo"]as? String ?? "" == "--agent--verify--success"{
                self.sendUserCenterRequest()
                self.presentAlertVc(confirmBtn: "确定", message: "", title: "已认证成功...", cancelBtn: nil, handler: { action in
                    self.backTapAction()
                }, viewController: self)
                return
            }
            self.sendAuthenConfirmRequest()
        }
    }
    func sendAuthenConfirmRequest() {
        let urlString = "\(URL_authen_msg_confirm)?type=1&phone=\(UserModel.shared.phone)"
        
        WHNetworkUtil.shareManager().GET(urlString: urlString) { responseObject in
            if responseObject["code"]as? Int ?? 0 == 200{
                self.sendUserCenterRequest()
                self.presentAlertVc(confirmBtn: "确定", message: "", title: "已认证成功...", cancelBtn: nil, handler: { action in
                    self.backTapAction()
                }, viewController: self)
            }else{
                self.presentAlertVcNoAction(title: "\(responseObject["message"]as? String ?? "网络请求错误，请稍后重试")", viewController: self)
            }
        }
    }
}
